package com.ailink.basic.nio;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Map;
import java.util.Set;

/**
 * Created by Administrator on 2018/10/26
 */
public class buffer {
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(10);
        buffer.put("abc".getBytes());
        buffer.put("def".getBytes());

        buffer.flip();
        byte[] dst = new byte[buffer.limit()];
        buffer.get(dst);
        System.out.println(new String(dst));
        buffer.rewind();
        byte[] dst1 = new byte[buffer.limit()];
        buffer.get(dst1);
        System.out.println(new String(dst1));

        buffer.clear();

        System.out.println(buffer.mark());
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());
    }

    public void testCharset() throws CharacterCodingException {
        Map<String, Charset> map = Charset.availableCharsets();
        Set<Map.Entry<String, Charset>> set = map.entrySet();
        for (Map.Entry entry : set) {
            System.out.println(entry.getKey() + "=" + entry.getValue());
        }

        Charset charset = Charset.forName("GBK");
        CharsetEncoder encoder = charset.newEncoder();
        CharsetDecoder decoder = charset.newDecoder();

        CharBuffer buffer = CharBuffer.allocate(1024);
        buffer.put("尚硅谷");
        buffer.flip();

        ByteBuffer byteBuffer = encoder.encode(buffer);
        CharBuffer buffer1 = decoder.decode(byteBuffer);
        System.out.println(buffer1.toString());

    }
}
